import React from 'react';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import Input from '../../components/base/Input.js';
import loginActionModule from '../../actions/loginAction.js';

const Login = withRouter(
  React.createClass({
    getInitialState() {
      return {
        buttonState: false,
        formData:{
          username: '',
          password: ''
        }
      };
    },
    handleChange(target) {
      const fData = this.state.formData;
      fData[target.name] = target.value;
      this.setState({
        formData: fData
      });
      // 如果有为空情况，不能点击保存按钮
      // ==============================
      for (const key in fData) {
        if (!fData[key]) {
          this.setState({
            buttonState: false
          });
          break;
        } else {
          this.setState({
            buttonState: true
          });
        }
      }
    },
    submitData() {
      const { loginAction } = this.props;
      loginAction(this.state.formData, this.props.router);
    },
    render() {
      const loginErrorMessage = <p className="login-error-msg">帐号或密码输入有误，请重新输入</p>;
      const button = <button onClick={this.submitData} className="btn btn-primary ">登录</button>;
      const disableButton = <button disabled="disabled" className="btn btn-disable ">登录</button>;
      return (
        <div className="login">
          <p className="login-title">登录</p>
          {this.props.errorState ? loginErrorMessage : ''}
          <div className="form-group">
            <div className="input-group">
              <Input
                type="text"
                onChange={this.handleChange}
                data-target="username"
                value={this.state.formData.username}
              />
            </div>
          </div>
          <div className="form-group">
            <div className="input-group">
              <Input
                type="password"
                onChange={this.handleChange}
                data-target="password"
                value={this.state.formData.password}
              />
            </div>
          </div>
            {this.state.buttonState ? button : disableButton}
        </div>
      );
    }
  })
);

const mapStateToProps = (state) => {
  return {
    errorState: state.login.error
  };
};
// export default Login
module.exports = connect(mapStateToProps, loginActionModule)(Login);
